//
//  WebService.m
//  KG
//
//  Created by Eugene Braginets on 17.03.12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "WebService.h"
#import "AppDelegate.h"

@implementation WebService
@synthesize response=_response;
@synthesize reqID=_reqID;
@synthesize dataType=_dataType;

//on success webService creates notification with name reqID passed on init
//This notification contains NSArray with three objects
//the first is the WebService's response
//the second one is the also reqID
//the third is dataType (@"news", @"players" etc.)

- (id)initWithURL:(NSURL *)url andRequestID:(NSString*)requestID andDataType:(NSString*) type {
	if (self = [super init])
	{
        //NSLog (@"WebService is here!");
        self.reqID=requestID;
        self.dataType=type;
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        
        NSLog(@"WebService request: %@",url);
		connection = [NSURLConnection connectionWithRequest:request delegate:self];
        
		[connection start];
	}
    
	return self;
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
	// every response could mean a redirect
	receivedData = nil;
    
	// need to record the received encoding
	// http://stackoverflow.com/questions/1409537/nsdata-to-nsstring-converstion-problem
    //NSLog (@"response: %@",response);
    //NSLog (@"TextEncoding: %@",[response textEncodingName]);
   
    CFStringRef encodingName;
    
  	if (![response textEncodingName]) {
         encodingName=(__bridge_retained CFStringRef) [NSString stringWithString:@"UTF-8"];
    }
    else {
    encodingName=(__bridge_retained CFStringRef) [response textEncodingName];
    }
    
    CFStringEncoding cfEncoding = CFStringConvertIANACharSetNameToEncoding(encodingName);
	
    encoding = CFStringConvertEncodingToNSStringEncoding(cfEncoding);
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
	[myAppDelegate setErrors:0];
    //NSLog (@"WebService:connection");
    if (!receivedData)
	{
		// no store yet, make one
		receivedData = [[NSMutableData alloc] initWithData:data];
	}
	else
	{
		// append to previous chunks
		[receivedData appendData:data];
	}
}

// all worked
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSString *json = [[NSString alloc] initWithData:receivedData encoding:encoding];
  	[self setResponse:json];
    NSArray* answer=[[NSArray alloc] initWithObjects:self.response,self.reqID, self.dataType,nil];
    
    [[NSNotificationCenter defaultCenter]
     postNotificationName:self.reqID
     object:answer];
    
   
//    NSLog(@"WebServer got answer %@", json);
    NSLog (@"WebService got answer for object: %@",self.dataType);
}

// and error occured

- (void) msg:(NSError*) error {
    
    
    if ([myAppDelegate errors]<3) {
        [myAppDelegate msg:[error localizedDescription]];
        [myAppDelegate setErrors:[myAppDelegate errors]+1];   
    }
    if ([myAppDelegate errors]==3)   
        [myAppDelegate msg:[NSString stringWithFormat:@"ERROR: %@",[error localizedDescription]]];
        
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
//    NSLog(@"ERROR: %@",[error localizedDescription]);
//    [self performSelectorOnMainThread:@selector(msg:) withObject:error waitUntilDone:YES];

}

// to deal with self-signed certificates
- (BOOL)connection:(NSURLConnection *)connection
canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
	return [protectionSpace.authenticationMethod
			isEqualToString:NSURLAuthenticationMethodServerTrust];
}

- (void)connection:(NSURLConnection *)connection
didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
	
    //NSLog(@"Host: %@",challenge.protectionSpace.host);
    
    
    if ([challenge.protectionSpace.authenticationMethod
		 isEqualToString:NSURLAuthenticationMethodServerTrust])
	{
		// we only trust our own domain
		if ([challenge.protectionSpace.host isEqualToString:@"kerrygaa.ie"])
		{
			NSURLCredential *credential =
            [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
			[challenge.sender useCredential:credential forAuthenticationChallenge:challenge];
		}
	}
    
	[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}


@end
